package com.fg.pro.trade.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.trade.dto.GmOrderDto;
import com.fg.pro.model.trade.dto.GmStockSheetDto;
import com.fg.pro.trade.dao.TradeStockSheetDao;
import com.fg.pro.trade.entity.TradeOrder;
import com.fg.pro.trade.entity.TradeOrderDetail;
import com.fg.pro.trade.entity.TradeStockSheet;
import com.fg.pro.trade.entity.TradeStockSheetDetail;
import com.fg.pro.trade.service.TradeStockSheetDetailService;
import com.fg.pro.trade.service.TradeStockSheetService;
import com.fg.pro.trade.utils.GmHttpUtils;
import jakarta.annotation.Resource;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

import static com.fg.pro.trade.utils.GmRequestUrl.GM_ORDER_URL;
import static com.fg.pro.trade.utils.GmRequestUrl.GM_STOCK_SHEET_URL;

/**
 * 库存变化-出入库总览(TradeStockSheet)表服务实现类
 *
 * @author makejava
 * @since 2025-08-20 10:10:15
 */
@Service("tradeStockSheetService")
public class TradeStockSheetServiceImpl extends ServiceImpl<TradeStockSheetDao, TradeStockSheet> implements TradeStockSheetService {
    @Autowired
    GmHttpUtils gmHttpUtils;
    @Autowired
    RedissonClient redissonClient;
    @Resource
    TradeStockSheetDetailService tradeStockSheetDetailService;


    @Override
    public boolean refresh(Date start, Date end) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    refreshTradeSheetByLock(start,end);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "refreshTradeSheetByLock");
        thread.start();
        return false;
    }


    @Transactional
    public boolean refreshTradeSheetByLock(Date start, Date end) throws InterruptedException {
        if (start == null || end == null) {
            start = new Date();
            end = new Date();
        }
        DateTime beginOfDay = DateUtil.beginOfDay(start);
        DateTime endOfDay = DateUtil.endOfDay(end);
        LinkedList<TradeStockSheet> newList = new LinkedList<>();
        LinkedList<TradeStockSheetDetail> detailList = new LinkedList<>();
// 获取请求参数 条件变量
        int num = 0;
        int limit = 50;
        while (true) {
            System.out.println("num-->" + num);
            System.out.println("offset-->" + num * limit);
            GmStockSheetDto.GmStockSheetReponse gmStockSheetReponse = gmHttpUtils.httpPostByToken(GM_STOCK_SHEET_URL, new GmStockSheetDto().new GmStockSheetRequest(beginOfDay, endOfDay, limit, num * limit), GmStockSheetDto.GmStockSheetReponse.class);
            for (GmStockSheetDto.GmStockSheetReponse.stockSheetData gmStockSheetData : gmStockSheetReponse.getStock_sheets()) {
                double sumRebatePrice = 0;
                TradeStockSheet tradeStockSheet = new TradeStockSheet();
                tradeStockSheet.setId(gmStockSheetData.getStock_sheet_id());
                tradeStockSheet.setCreateTime(new Date(gmStockSheetData.getCreate_time()));
                tradeStockSheet.setUpdateTime(new Date(gmStockSheetData.getUpdate_time()));
                tradeStockSheet.setStockSheetType(gmStockSheetData.getSheet_type());
                tradeStockSheet.setStockSheetGroupId(gmStockSheetData.getGroup_id());
                tradeStockSheet.setStockSheetStationId(gmStockSheetData.getStation_id());
                tradeStockSheet.setStockSheetTargetId(gmStockSheetData.getTarget_id());
                tradeStockSheet.setSheetStatus(gmStockSheetData.getSheet_status());
                tradeStockSheet.setSubmitTime(new Date(gmStockSheetData.getSubmit_time()));
                if (gmStockSheetData.getCommit_time()!=null) {
                    tradeStockSheet.setCommitTime(new Date(gmStockSheetData.getCommit_time()));
                }
                tradeStockSheet.setStockSheetCreatorId(gmStockSheetData.getCreator_id());
                tradeStockSheet.setStockSheetTotalPrice(gmStockSheetData.getTotal_price());
                tradeStockSheet.setStockSheetTargetType(gmStockSheetData.getTarget_type());
                tradeStockSheet.setStockSheetBatchIndex(gmStockSheetData.getBatch_index());
                tradeStockSheet.setStockSheetPayStatus(gmStockSheetData.getPay_status());
                tradeStockSheet.setStockSheetTaxTotalPrice(gmStockSheetData.getTax_total_price());
                tradeStockSheet.setStockSheetProductTotalPrice(gmStockSheetData.getTotal_price());
                tradeStockSheet.setStockSheetSupplierId(gmStockSheetData.getSupplier_id());
                tradeStockSheet.setStockSheetTotalPriceNoTax(gmStockSheetData.getTotal_price_no_tax());
                tradeStockSheet.setStockSheetWarehouseId(gmStockSheetData.getWarehouse_id());
                tradeStockSheet.setStockSheetSubmitterId(gmStockSheetData.getSubmitter_id());
                tradeStockSheet.setStockSheetApproverId(gmStockSheetData.getApprover_id());
                tradeStockSheet.setStockSheetPurchasePattern(gmStockSheetData.getPurchase_pattern());
                tradeStockSheet.setStockSheetDetailLen(gmStockSheetData.getDetail_len());
                tradeStockSheet.setStockSheetStockSheetSerialNo(gmStockSheetData.getStock_sheet_serial_no());
                tradeStockSheet.setStockSheetPrintedCount(gmStockSheetData.getPrinted_count());

                newList.add(tradeStockSheet);
                int size = gmStockSheetData.getDetails().size();
                for (GmStockSheetDto.GmStockSheetReponse.stockSheetData.GmStockSheetDetailData gmDetail : gmStockSheetData.getDetails()) {
                    TradeStockSheetDetail tradeStockSheetDetail = new TradeStockSheetDetail();
                    tradeStockSheetDetail.setId(gmDetail.getStock_sheet_detail_id());
                    tradeStockSheetDetail.setCreateTime(gmDetail.getCreate_time()==null?null:new Date(gmDetail.getCreate_time()));
                    tradeStockSheetDetail.setUpdateTime(gmDetail.getUpdate_time()==null?null:new Date(gmDetail.getUpdate_time()));
                    tradeStockSheetDetail.setStockSheetDetailGroupId(gmDetail.getStock_sheet_detail_id());
                    tradeStockSheetDetail.setStockSheetDetailStationId(gmDetail.getStation_id());
                    tradeStockSheetDetail.setStockSheetId(gmDetail.getStock_sheet_id());
                    tradeStockSheetDetail.setSkuId(gmDetail.getSku_id());
                    tradeStockSheetDetail.setStockSheetDetailBaseUnitId(gmDetail.getBase_unit_id());
                    tradeStockSheetDetail.setStockSheetDetailSkuUnitId(gmDetail.getSku_unit_id());
                    tradeStockSheetDetail.setStockSheetDetailAmount(gmDetail.getAmount());
                    tradeStockSheetDetail.setStockSheetDetailOperatorId(gmDetail.getOperator_id());
                    tradeStockSheetDetail.setStockSheetDetailCreatorId(gmDetail.getCreator_id());
                    tradeStockSheetDetail.setStockSheetDetailInputTax(gmDetail.getInput_tax());
                    tradeStockSheetDetail.setStockSheetDetailTaxAmount(gmDetail.getTax_amount());
                    tradeStockSheetDetail.setStockSheetDetailTaxInputPrice(gmDetail.getTax_input_price());
                    tradeStockSheetDetail.setStockSheetDetailOriginTaxInputPrice(gmDetail.getOrigin_tax_input_price());
                    tradeStockSheetDetail.setStockSheetDetailShelfId(gmDetail.getShelf_id());
                    tradeStockSheetDetail.setStockSheetDetailQuantity(gmDetail.getQuantity());
                    tradeStockSheetDetail.setStockSheetDetailPrice(gmDetail.getPrice());
                    tradeStockSheetDetail.setStockSheetDetailSourceQuantity(gmDetail.getSource_quantity());
                    tradeStockSheetDetail.setStockSheetDetailSheetType(gmDetail.getSheet_type());
                    tradeStockSheetDetail.setStockSheetDetailStockSheetSerialNo(gmDetail.getStock_sheet_serial_no());
                    tradeStockSheetDetail.setStockSheetDetailSheetStatus(gmDetail.getSheet_status());
                    tradeStockSheetDetail.setStockSheetDetailWarehouseId(gmDetail.getWarehouse_id());
                    tradeStockSheetDetail.setSubmitTime(new Date(gmDetail.getSubmit_time()));
                    tradeStockSheetDetail.setStockSheetDetailSupplierId(gmDetail.getSupplier_id());
                    tradeStockSheetDetail.setStockSheetDetailReceiveStatus(gmDetail.getReceive_status());
                    tradeStockSheetDetail.setStockSheetDetailPurchasePrice(gmDetail.getPurchase_price());
                    tradeStockSheetDetail.setStockSheetDetailCreateTime(gmDetail.getCreate_time()==null?null:new Date(gmDetail.getCreate_time()));
                    tradeStockSheetDetail.setStockSheetDetailInputUnitId(gmDetail.getInput_unit_id());
                    tradeStockSheetDetail.setStockSheetDetailInputUnitQuantity(gmDetail.getInput_unit_quantity());
                    tradeStockSheetDetail.setStockSheetDetailSkuBatchType(gmDetail.getSku_batch_type());
                    tradeStockSheetDetail.setStockSheetDetailAmountTcerror(gmDetail.getAmount_tcerror());
                    tradeStockSheetDetail.setStockSheetDetailPlanQuantity(gmDetail.getPlan_quantity());
                    tradeStockSheetDetail.setStockSheetDetailInputUnitPlanQuantity(gmDetail.getInput_unit_plan_quantity());
                    tradeStockSheetDetail.setStockSheetDetailIsDeleted(gmDetail.getSku_is_deleted());

                    if (tradeStockSheet.getStockSheetType()==320) {
                        Double stockSheetTotalPriceNoTax = tradeStockSheet.getStockSheetTotalPriceNoTax();
                        Double stockSheetTotalPrice = tradeStockSheet.getStockSheetTotalPrice();
                        if (stockSheetTotalPriceNoTax!=null) {
                            sumRebatePrice = NumberUtil.sub(stockSheetTotalPriceNoTax, stockSheetTotalPrice);
                            tradeStockSheet.setStockSheetRebatePrice(sumRebatePrice);
                        }
                        Double rebatePrice = NumberUtil.div(sumRebatePrice, size);
                        tradeStockSheetDetail.setStockSheetDetailRebatePrice(NumberUtil.add(tradeStockSheetDetail.getStockSheetDetailTaxAmount(),rebatePrice));
                    }
                    detailList.add(tradeStockSheetDetail);
                }
            }
            if (!gmStockSheetReponse.getPaging().has_more) {
                break;
            }
            num+=1;
            TimeUnit.SECONDS.sleep(2);
        }
        tradeStockSheetDetailService.saveOrUpdateBatch(detailList);
        boolean save = saveOrUpdateBatch(newList);
        return save;
    }
}

